/**
 * 
 */
package monitor;

import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * @author Robbie
 * 
 * The Maker class is part of the plug-in infrastructure.  All 
 * plug-ins must extend from this class.
 *
 */
public class Maker extends Thread implements PropertyChangeListener {

	private String myPacketID;
	private String myPacketData;
	
	private PropertyChangeSupport listeners = new PropertyChangeSupport(this);
	
	public Maker(String pktID){
		if(pktID.length()!=8){
			try {
				throw new Exception("Packet ID is not 8 characters");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		myPacketID = pktID;
		myPacketData = new String();
	}
	
	protected void setPacketData(String data){
		synchronized(myPacketData){myPacketData = data;}
	}
	
	protected void broadcastPacket(){
		String hex = Integer.toString(myPacketData.length(), 16);
		if(hex.length()==1){hex = "000" + hex;}
		else if(hex.length()==2){hex = "00" + hex;}
		else if(hex.length()==3){hex = "0" + hex;}
		String packet = myPacketID + hex + myPacketData;
		PropertyChangeEvent e = new PropertyChangeEvent(this,"PACKET", null, packet);
		scheduleUpdate(e);
	}
	
	/**
	 * Adds a property change listener
	 * 
	 * @param l listener to add
	 */
	public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
	    listeners.addPropertyChangeListener(l);
	}
	
	/**
	 * Removes a property change listener
	 * 
	 * @param l listener to remove
	 */
	public synchronized void removePropertyChangeListener(PropertyChangeListener l) {
	    listeners.removePropertyChangeListener(l);
	}
	
	private void fireUpdate(PropertyChangeEvent evt) {
	    listeners.firePropertyChange(evt);
	}


	private void scheduleUpdate(final PropertyChangeEvent evt) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				fireUpdate(evt);
			}
		});
	}

	/**
	 * This method should be overridden by child classes.
	 */
	public void propertyChange(PropertyChangeEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
